package cn.net.lwj.moredb.config;

import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

@Configuration
@MapperScan(basePackages = "cn.net.lwj.moredb.mapper.mysql",sqlSessionFactoryRef = "mysqlSqlSessionFactory")
public class MysqlDataSourceConfig {
 
    @Bean(name = "mysqlDataSource") //注入到这个容器
    @Primary  //#primary是设置优先，因为有多个数据源，在没有明确指定用哪个的情况下，会用带有primary的，这个注解必须有一个数据源要添加
    @ConfigurationProperties("spring.datasource.mysql") //表示取application.properties配置文件中的前缀
    public DataSource MysqlDataSource(){
        return DataSourceBuilder.create().build();
    }

    //@Qualifier("xxx")的含义是告诉他使用哪个DataSource
    @Bean(name = "mysqlSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("mysqlDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/mysql/*.xml"));
        return sessionFactoryBean.getObject();
    }
    @Bean(name = "mysqlTransactionManager")//配置事务
    @Primary
    public DataSourceTransactionManager MysqlTransactionManager(){
        return new DataSourceTransactionManager(MysqlDataSource());
        //return null;
    }

}